package org.fatmansoft.teach.util;

import com.alibaba.fastjson.JSONObject;
import org.fatmansoft.teach.payload.request.DataRequest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utils {
    //    用于解析前端传入的数据
    public static String parseRequest(DataRequest request, String key, Map map ) {
        String result = "";
        try {
            if (request.getData().get(key) != null && request.getData().get(key).toString() != "")
                result = request.getData().get(key).toString();
        } catch (Exception e) {
            map.put("message", e.getMessage());
            e.printStackTrace();
        }

        if (!result.equals("")) return result;
        else return null;
    }

    public static Map<String, Object> toMap(String mapStr){
        Map<String,Object> map = new HashMap<>();
        if(mapStr.length() > 0){
            //将字符串转换为StringBuilder,并将字符串两头的花括号删掉
            StringBuilder sb = new StringBuilder(mapStr);
            sb.delete(0, 1).delete(sb.length()-1,sb.length());
            //将StringBuilder转换为字符串，接着转换为List数组
            String str = sb.toString();
            List<String> strList = Arrays.asList(str.split(","));
            //循环数组
            for (int i = 0; i < strList.size(); i++) {
                //得到字符串第一个等号的下标
                int index = strList.get(i).indexOf("=");
                //截取字符串等号前半部分 做为map的key。
                String key = strList.get(i).substring(0, index);
                //截取字符串等号后半部分，作为map的value；
                String value = strList.get(i).substring(index+1, strList.get(i).length());
                map.put(key, value);
            }
        }
        return map;
    }

    //    用来判断传入的字符串是否为纯数字
    public static boolean checkNum(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c < '0' || c > '9') return false;
        }
        return true;
    }

    public static boolean hasInfo(String str){
        if(str.equals("") | str == null) return false;
        return true;
    }
}
